<template>
  <div>
    <!--  面包屑导航-->
    <Breadcrumb></Breadcrumb>
    <!--  卡片视图-->
    <el-card>
<!--      头部按钮-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddDialog">添加角色</el-button>
        </el-col>
      </el-row>
<!--      表格-->
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand" width="45px" >
          <template v-slot:default="scope">
             <el-row  :class="['bdbottom',i1==0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
               <!-- 渲染一级权限-->
               <el-col :span="5">
                  <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                 <i class="el-icon-right"></i>
               </el-col>
<!--               渲染二级权限 -->
               <el-col :span="19">
                 <el-row :class="[i2==0 ? '': 'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                   <el-col :span="6">
                     <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                     <i class="el-icon-right"></i>
                   </el-col>
<!--                   渲染三级权限-->
                   <el-col :span="18">
                     <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">
                       {{item3.authName}}
                     </el-tag>
                   </el-col>
                 </el-row>
               </el-col>
             </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="45px"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="150px"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="250px"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope" >
            <!--              编辑-->
            <el-tooltip class="item" effect="dark" content="修改" placement="top" >
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
            </el-tooltip>
            <!--              删除-->
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scope.row.id)">删除</el-button>
            </el-tooltip>
            <!--              分配-->
            <el-tooltip class="item" effect="dark" content="分配" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--      添加角色对话框-->
    <el-dialog
        title="添加角色"
        :visible.sync="addRoleVisible"
        width="40%"
        @close="addDialogClosed" >
      <el-form ref="form" :model="roleForm" label-width="80px" :rules="addRoleFormRules">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
    </el-dialog>


    <!--      编辑角色对话框-->
    <el-dialog
        title="编辑角色"
        :visible.sync="editRoleVisible"
        width="40%"
     >
      <el-form ref="editRoleForm" :model="editForm" label-width="80px" :rules="editRoleFormRules">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </span>
    </el-dialog>
    <!--      分配权限对话框-->
    <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="40%"
        @close="setRightDialogClosed"
    >
      <el-tree :props="treeProps" ref='treeRef' :data="rightsList" show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="checkedKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRight">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "@/components/Breadcrumb";
export default {
  name: "Roles",
  components: {Breadcrumb},
  data() {
    return {
      roleList: [],
      addRoleVisible: false,
      roleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFormRules: {
        roleName: [
          {required: true, message: "请输入角色名字", trigger: "blur"},

        ]
      },
      editRoleVisible: false,
      editRoleFormRules: {
        roleName: [
          {required: true, message: "请输入角色名字", trigger: "blur"},
        ]
      },
      editForm: {},
      setRightDialogVisible: false,
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      checkedKeys: [],
      roleId: ''


    }
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取所有角色列表
    async getRolesList() {
      try {
        const {data: res} = await this.axios.get('roles');
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.roleList = res.data;
      } catch (e) {
        this.$message.error("服务器出错请联系管理员")
      }
    },
    addDialogClosed() {
      this.$refs.form.resetFields();
    },
    //展示添加对话框
    showAddDialog() {
      this.addRoleVisible = true;
    },
    addRole() {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }
        try {
          const {data: res} = await this.axios.post('roles', this.roleForm);
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg);
          }
          this.getRolesList();
          this.addRoleVisible = false;
          this.$message.success(res.meta.msg);

        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      })
    },

    //展示修改对话框
    async showEditDialog(id) {
      this.editRoleVisible = true
      try {
        const {data: res} = await this.axios.get(`roles/${id}`);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.editForm = res.data
      } catch (e) {
        this.$message.error("服务器出错请联系管理员");
      }
    },

    //发送请求修改角色
    editRole() {
      this.$refs.editRoleForm.validate(async valid => {
        if (!valid) {
          return;
        }
        try {
          const {data: res} = await this.axios.put(`roles/${this.editForm.roleId}`, {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          });
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.getRolesList();
          this.editRoleVisible = false;
          this.$message.success("修改成功");
        } catch (e) {
          this.$message.error("服务器出错请联系管理员");
        }
      })
    },
    //通过id删除角色
    removeRoleById(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const {data: res} = await this.axios.delete(`roles/${id}`);
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getRolesList();
        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //通过id删除权限
    removeRightById(row, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const {data: res} = await this.axios.delete(`roles/${row.id}/rights/${rightId}`);
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          row.children = res.data
          this.$message({
            type: 'success',
            message: res.meta.msg
          });

        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 展示分配权限对话框
    async showSetRightDialog(row) {
      this.setRightDialogVisible = true;
      this.roleId = row.id
      try {
        const {data: res} = await this.axios.get('rights/tree');
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.rightsList = res.data;

        row.children.forEach(it => {
          this.getLeafKeys(it, this.checkedKeys)
        })
        this.$message.success(res.meta.msg)
      } catch (e) {
        this.$message.error(e)
      }
    },
    //递归查询选中的权限id
    getLeafKeys(node, arr) {
      //如果当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr);
      })
    },
    setRightDialogClosed() {
      this.checkedKeys = [];
    },
    //发送请求分配权限
    async setRight() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()];
      const idStr = keys.join(',')
      try {
        const {data: res} = await this.axios.post(`roles/${this.roleId}/rights`, {rids: idStr});
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.getRolesList();
        this.setRightDialogVisible = false
        this.$message.success(res.meta.msg)
      } catch (e) {
        this.$message.error(e)
      }
    }





  },
}
</script>

<style scoped>
.el-table{
  margin-top: 15px;
}
.el-tag{
  margin: 5px ;
}
.bdtop{
  border-top:1px solid cornflowerblue;
}
.bdbottom{
  border-bottom:1px solid cornflowerblue;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
